package org.wisdom.ac.domain.user.repository.dao.impl;

import org.springframework.transaction.annotation.Transactional;
import org.wisdom.ac.domain.user.entity.AcUser;
import org.wisdom.ac.domain.user.repository.dao.UserDao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import java.util.List;

/**
 * 系统用户仓储扩展
 *
 * @author 张智研
 * @date 2022/05/30 22:11
 **/
public class UserDaoImpl implements UserDao {

    @PersistenceContext
    private EntityManager em;

    @Override
    public List<AcUser> findAllByRoleId(Iterable<String> roleIds) {
        String jpql =
            "select distinct u from AcUser u left outer join AcUserRole ur on u.id = ur.userId and ur.roleId in (:roleIds)";
        TypedQuery<AcUser> query = this.em.createQuery(jpql, AcUser.class);

        query.setParameter("roleIds", roleIds);
        // 去除N+1查询
        query.setHint("javax.persistence.fetchgraph", this.em.getEntityGraph("userWithRole"));
        return query.getResultList();
    }

    @Transactional
    @Override
    public void updatePassword(String userId, String password) {
        String jpql = "update AcUser u set u.password = :password where u.id = :userId";
        Query query = this.em.createQuery(jpql);
        query.setParameter("userId", userId);
        query.setParameter("password", password);
        query.executeUpdate();
    }
}
